package com.wbao.dianniu.tabstrip.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.ext.sns.TIMFriendFutureItem;
import com.tencent.qcloud.timchat.utils.Conversation;
import com.tencent.qcloud.timchat.utils.ConversationAdapter;
import com.tencent.qcloud.timchat.utils.ConversationPresenter;
import com.tencent.qcloud.timchat.utils.ConversationView;
import com.tencent.qcloud.timchat.utils.CustomMessage;
import com.tencent.qcloud.timchat.utils.FriendshipMessageView;
import com.tencent.qcloud.timchat.utils.MessageFactory;
import com.tencent.qcloud.timchat.utils.NomalConversation;
import com.tencent.qcloud.timchat.utils.PushUtil;
import com.wbao.dianniu.R;
import com.wbao.dianniu.db.TencentUserBean;
import com.wbao.dianniu.db.TencentUserHelper;
import com.wbao.dianniu.fragment.LazyLoadBaseFragment;
import com.wbao.dianniu.ui.MainActivity;
import com.wbao.dianniu.update.ChatUnreadChangeManger;
import com.wbao.dianniu.update.ImChangerManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 消息
 * <p>
 * Created by yejianjun on 2018/8/10.
 */

public class ConversationFragment extends LazyLoadBaseFragment implements ConversationView, FriendshipMessageView, ConversationAdapter.OnItemClickListener, ImChangerManager.ImChangerListener {
    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    private String TAG = ConversationFragment.class.getSimpleName();
    private View view;
    private List<Conversation> conversationList = new LinkedList<>();
    private ConversationAdapter adapter;
    private ListView listView;
    private ConversationPresenter presenter;
    //    private FriendshipManagerPresenter friendshipManagerPresenter;
//    private FriendshipConversation friendshipConversation;
    private TextView noDataTV;
    private boolean isExpand;
//    private static ConversationFragment instance;


    public static ConversationFragment instance() {
        /*if (null == instance) {
            instance = new ConversationFragment();
        }*/
        ConversationFragment view = new ConversationFragment();

//        instance = new ConversationFragment();
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        //在配置变化的时候将这个fragment保存下来
        setRetainInstance(true);
        super.onCreate(savedInstanceState);
        ImChangerManager.getInstance().addListener(this);
    }

    /*@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_conversation, container, false);
            initWattingView(view);
            listView = (ListView) view.findViewById(R.id.conversation_list);
            noDataTV = (TextView) view.findViewById(R.id.no_message_tv);
            adapter = new ConversationAdapter(getContext(), R.layout.conversation_list_item, conversationList);
            adapter.setOnItemClickListener(this);
            listView.setAdapter(adapter);
            presenter = new ConversationPresenter(this);
            presenter.getConversation();
            registerForContextMenu(listView);
        }
        adapter.notifyDataSetChanged();
        return view;
    }*/

    private void initWattingView(View view) {
        waittingLayout = view.findViewById(R.id.waitting_layout);
        waittingProBar = view.findViewById(R.id.waitting_progress);
        waittingTV = view.findViewById(R.id.waitting_text_desc);
    }

    @Override
    public void initView(List<TIMConversation> conversationList) {
        waittingLayout.setVisibility(View.GONE);
        this.conversationList.clear();
        for (TIMConversation item : conversationList) {
            switch (item.getType()) {
                case C2C:
                case Group:
                    this.conversationList.add(new NomalConversation(item));
                    break;
            }
        }
//        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    @Override
    public void updateMessage(TIMMessage message) {
//        Log.d(TAG, "updateMessage...");
        if (message == null) {
            adapter.notifyDataSetChanged();
            return;
        }
        if (message.getConversation().getType() == TIMConversationType.System) { // 屏蔽系统消息
//            groupManagerPresenter.getGroupManageLastMessage();
            return;
        }
        if (MessageFactory.getMessage(message) instanceof CustomMessage) return;
        NomalConversation conversation = new NomalConversation(message.getConversation());
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation c = iterator.next();
            if (conversation.equals(c)) {
                conversation = (NomalConversation) c;
                iterator.remove();
                break;
            }
        }

        conversation.setLastMessage(MessageFactory.getMessage(message));
        List<TencentUserBean> beanList = TencentUserHelper.queryTencentUser(conversation.getIdentify());
        if (null != beanList && beanList.size() > 0) {
//            Log.e(TAG, " 查询到本地缓存数据，..niceName:" + beanList.get(0).getNiceName() + "  faceUrl:" + beanList.get(0).getFaceUrl());
            conversation.setName(beanList.get(0).getNiceName());
            conversation.setUrl(beanList.get(0).getFaceUrl());
        } else { // 如果没有本地缓存数据，则请求后台
//            Log.e(TAG, " 没有本地缓存数据，请求服务器.." + conversation.getIdentify());
            List<String> users = new ArrayList<>();
            users.add(conversation.getIdentify());
            presenter.reqUserProfile(users);
        }
        conversationList.add(conversation);
        refresh();
    }

    @Override
    public void updateFriendshipMessage() {
//        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    @Override
    public void removeConversation(String identify) {
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation conversation = iterator.next();
            if (conversation.getIdentify() != null && conversation.getIdentify().equals(identify)) {
                iterator.remove();
                adapter.notifyDataSetChanged();
                return;
            }
        }
    }

    @Override
    public void refresh() {
        Collections.sort(conversationList);
        adapter.notifyDataSetChanged();
        if (conversationList.size() == 0) {
            noDataTV.setVisibility(View.VISIBLE);
        } else {
            noDataTV.setVisibility(View.GONE);
        }

        if (getActivity() instanceof MainActivity) {
            int count = getTotalUnreadNum();
            ((MainActivity) getActivity()).setChatUnread(count);
            ChatUnreadChangeManger.getInstance().setChatUnread(count);
        }
    }

    @Override
    public void updateHeadUrlAndName(List<TIMUserProfile> timUserProfiles) {
        for (TIMUserProfile res : timUserProfiles) {
            for (Conversation conversation : conversationList) {
                if (res.getIdentifier().equals(conversation.getIdentify())) {
                    conversation.setUrl(res.getFaceUrl());
                    conversation.setName(res.getNickName());
//                    Log.e(TAG, "  更新头像数据。。。 identifier: " + res.getIdentifier() + " nickName: " + res.getNickName()
//                            + " remark: " + res.getRemark() + " url:" + res.getFaceUrl());
                }
            }
        }
        refresh();
    }

    @Override
    public void onGetFriendshipLastMessage(TIMFriendFutureItem message, long unreadCount) {
        /*Log.d(TAG, "onGetFriendshipLastMessage...");
        if (friendshipConversation == null) {
            friendshipConversation = new FriendshipConversation(message);
        } else {
            friendshipConversation.setLastMessage(message);
        }
        friendshipConversation.setUnreadCount(unreadCount);

        if (!conversationList.contains(friendshipConversation)) {
            conversationList.add(friendshipConversation);
        }
        Collections.sort(conversationList);
        refresh();
        */
    }

    @Override
    public void onGetFriendshipMessage(List<TIMFriendFutureItem> message) {
//        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
        PushUtil.getInstance().reset();
    }

    public int getTotalUnreadNum() {
        int num = 0;
        for (Conversation conversation : conversationList) {
            num += conversation.getUnreadNum();
        }
        return num;
    }

    @Override
    public void itemClick(View view) {
        final int position;
        switch (view.getId()) {
            case R.id.btnDelete:
                position = (Integer) view.getTag(R.id.btnDelete);
                presenter.delConversationNot(TIMConversationType.C2C, conversationList.get(position).getIdentify());
                break;
            case R.id.btnTop:
                position = (Integer) view.getTag(R.id.btnTop);
                break;
            case R.id.conversation_item_layout:
                position = (Integer) view.getTag(R.id.conversation_item_layout);
                conversationList.get(position).navToDetail(getActivity());
                break;

            default:
                break;
        }
    }


    /*public void setIsExpand(boolean expand) {
        isExpand = expand;
    }

    public boolean getIsExpand() {
        return isExpand;
    }*/

    @Override
    public void onDestroy() {
        super.onDestroy();
        /*if (null != instance) {
            instance = null;
        }*/
        ImChangerManager.getInstance().removeListener(this);
    }

    @Override
    public void imUserInfoChange(String identify, String niceName, String toUrl) {
//        Log.e(TAG, "imUserInfoChange...." + identify);
        for (int i = 0; i < conversationList.size(); i++) {
            if (conversationList.get(i).getIdentify().equals(identify)) {
                conversationList.get(i).setName(niceName);
                conversationList.get(i).setUrl(toUrl);
//                Log.e(TAG, "imUserInfoChange.... success " + i);
                break;
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_conversation;
    }

    private void reqData() {
        presenter = new ConversationPresenter(this);
        presenter.getConversation();
        adapter.notifyDataSetChanged();
    }


    @Override
    protected void initView(View view) {
        initWattingView(view);
        listView = (ListView) view.findViewById(R.id.conversation_list);
        noDataTV = (TextView) view.findViewById(R.id.no_message_tv);
        adapter = new ConversationAdapter(getContext(), R.layout.conversation_list_item, conversationList);
        adapter.setOnItemClickListener(this);
        listView.setAdapter(adapter);
        registerForContextMenu(listView);
        reqData();
    }

   /* @Override
    public void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
    }*/
}
